package top.ikunikun.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import top.ikunikun.common.BaseContext;
import top.ikunikun.common.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 过滤器对请求进行过滤
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                // 移动端发送短信
                "/user/sendMsg",
                // 移动端登陆
                "/user/login",

                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
        };
        boolean check = check(urls, requestURI);
        if(check) {
            log.info("放行无需登录请求:{}",requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        if(request.getSession().getAttribute("employee") != null) {
            log.info("放行已登录请求:{}",requestURI);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        // 手机端验证登陆
        if(request.getSession().getAttribute("user") != null) {
            log.info("放行已登录请求:{}",requestURI);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        log.info("拦截非登录请求:{}",requestURI);
        response.getWriter().write(JSON.toJSONString(Result.error("NOT LOGIN")));
    }

    /**
     * 路径匹配器
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            if (PATH_MATCHER.match(url,requestURI)) {
                return true;
            }
        }
        return false;
    }
}
